<?php 
class ControllerProductCategory extends Controller {  
	public function index() { 
		$this->language->load('product/category');  	    
		$this->load->model('catalog/category');
		$this->load->model('tool/seo_url');  		
        $this->document->breadcrumbs = array(); 
          
		if (isset($this->request->get['path'])) {
			$path = '';   		
			$parts = explode('_', $this->request->get['path']);                
			$category_id = array_pop($parts);
            
            $categories_list = explode('_', $this->request->get['path']);                         
            $this->document->breadcrumbs = $this->model_catalog_category->createBreadcrumbs($categories_list);
            
            /*
            $breadcrumbs = explode('_', $this->request->get['path']); 
            $breadcrumb_path = '';
            foreach($breadcrumbs as $breadcrumb){
                $separator = $breadcrumb_path ? ' >> '  : false;
                $breadcrumb_path = $breadcrumb_path ? ($breadcrumb_path . '_' . $breadcrumb) : $breadcrumb;
                
                $this->document->breadcrumbs[] = array(
                    'href'      => $this->model_tool_seo_url->rewrite(HTTP_SERVER . 'index.php?route=product/categories&path=' . $breadcrumb_path),
                    'text'      => $this->model_catalog_category->getCategoryName($breadcrumb),
                    'separator' => $separator,
                );
            }
            */           
		} 
        else {
			$category_id = 0;
		}
		$this->data['template'] = $this->config->get('config_template');
        $this->data['back'] = HTTP_SERVER . 'index.php?route=product/categories&path=' . implode('-', $parts);            
        $this->data['back_product'] = null;
        array_pop($this->document->breadcrumbs);
        //$this->data['breadcrumbs'] = $this->document->breadcrumbs;
    
		$category_info = $this->model_catalog_category->getCategory($category_id);	
		if ($category_info) {
            /*
            $this->document->breadcrumbs[] = array(
                'href'      => HTTP_SERVER . 'index.php?route=common/home',
                'text'      => $this->language->get('text_home'),
                'separator' => FALSE
            );
            */
            //$this->data['breadcrumbs'][] = array(
            $this->document->breadcrumbs[] = array(
                'href'      => '',
                'text'      => $category_info['name'],
                'separator' => ' >> ',
            );
            
	  		$this->document->title = $category_info['meta_title'] ? $category_info['meta_title'] : $category_info['name'];  			
			$this->document->keywords = $category_info['meta_keywords']; 			
			$this->document->description = $category_info['meta_description'];  
			
			$this->data['heading_title'] = $category_info['name'];   			
			$this->data['description'] = html_entity_decode($category_info['description'], ENT_QUOTES, 'UTF-8');      			
			$this->data['text_sort'] = $this->language->get('text_sort');
            $this->data['breadcrumbs'] = $this->document->breadcrumbs;

			if (isset($this->request->get['page'])) {
				$page = $this->request->get['page'];      
			}
            else { 
				$page = 1;
			}	

            if (isset($this->request->get['sort'])) {
                $sort = $this->request->get['sort'];
            } 
            else {
                //$sort = 'p.sort_order';
                //$sort = 'pcs.product_sort_order';
				$sort = 'p.date_added';
            }
            $this->data['sort'] = $sort; 
            
			if (isset($this->request->get['order'])) {
				$order = $this->request->get['order'];
			} 
            else {
				//$order = 'ASC';
				$order = 'DESC';
			}
            $this->data['order'] = $order; 
            
            if (isset($this->request->get['limit'])) {                
                $limit = $this->request->get['limit'];
                $limit = $limit == 'none' ? 0 : $limit;
            }
            else{
                //$limit = 12;
				//$limit = 24;
                //$limit = 9;
                $limit = $this->isMobileEnabled() ? 8 : 9;
            }
			
            $attribute_ids = array();
			$selected_values = array();   
            $attribute_list = array(); 
            $attr_list = '';
			/*
            if(isset($this->request->get['attribute']) && is_array($this->request->get['attribute'])){
                $attribute_ids = $this->request->get['attribute'];
            }
            
            foreach($attribute_ids as $attribute_id){        
                foreach($attribute_id as $key => $val){                                
                    $attribute_list[] = $key;
                    $selected_values[] = $val;
                    $attr_list .= '&attribute[][' . $key . ']=' . $val;
                }
            }
            $attribute_list = array_unique($attribute_list);
			*/
			
			$this->load->model('catalog/product'); 
            $this->load->model('catalog/discount'); 
			/*
			if($attribute_list){
                $product_total = $this->model_catalog_product->getTotalProductsByCategoryAttribute($category_id, $attribute_list, $selected_values);
            }
            else{
                $product_total = $this->model_catalog_product->getTotalProductsByCategoryId($category_id);
            }
            */	
			//$product_total = $this->model_catalog_product->getTotalProductsByCategoryId($category_id);  
			
			$current_size = isset($this->request->get['product_size']) ? (int)$this->request->get['product_size'] : 0;			
			$selected_values = array($current_size);
			$this->load->model('catalog/attribute');
			$attributes = $this->model_catalog_attribute->getOptionsByCategory($category_id);
			
			$this->data['current_size'] = $current_size;
			$this->data['filter_size'] = $this->model_tool_seo_url->rewrite(HTTP_SERVER . 'index.php?route=product/category&path=' . $this->request->get['path'] . '&sort=' . $sort . '&order=' . $order . '&limit=' . $limit . '&product_size=');
			
			$t_attributes = array();
			foreach($attributes as $attribute){
				$t_attributes[] = array(					
					'value_id'  => $attribute['attribute_value_id'],
					'name'     	=> $attribute['name'],
					//'current'   => $current_size == $attribute['value_id'],  
					//'href'      => $this->model_tool_seo_url->rewrite(HTTP_SERVER . 'index.php?route=product/category&path=' . $this->request->get['path'] . '&sort=' . $sort . '&order=' . $order . '&limit=' . $limit . '&product_size=' . $attribute['value_id'])					
				);
			}	
			$this->data['attributes'] = array(); //$attributes;	
			$this->data['attributes'][] = array('attribute_values' => $t_attributes);
			
			if($current_size){
                $product_total = $this->model_catalog_product->getTotalProductsByCategoryAttribute($category_id, null, $selected_values);
            }
            else{
                $product_total = $this->model_catalog_product->getTotalProductsByCategoryId($category_id);
            }
			
            if ($product_total) {  
                $this->load->model('tool/image');             
				$this->data['button_add_to_cart'] = $this->language->get('button_add_to_cart');		
                 		
				$this->data['products'] = array();  
				/*
                if($attribute_list){     		
                    $results = $this->model_catalog_product->getProductsByCategoryAttributeSortPrice($category_id, $attribute_list, $selected_values, $sort, $order, $limit, $page);				
                }
                else{
                    $results = $this->model_catalog_product->getProductsByCategoryIdSortPrice($category_id, $sort, $order, $limit, $page);   
                }
                */
				//$results = $this->model_catalog_product->getProductsByCategoryIdSortPrice($category_id, $sort, $order, $limit, $page);   
								
        		if($current_size){     		
                    $results = $this->model_catalog_product->getProductsByCategoryAttributeSortPrice($category_id, null, $selected_values, $sort, $order, $limit, $page);				
                }
                else{
                    $results = $this->model_catalog_product->getProductsByCategoryIdSortPrice($category_id, $sort, $order, $limit, $page);   
                }
				
				foreach ($results as $result) {  
					if ($result['image']) {
						$image = $result['image'];
					} 
                    else {
						$image = 'no_image.jpg';
					} 					
					    
                    /*         
					$special = FALSE; 					
					$discount = $this->model_catalog_product->getProductDiscount($result['product_id']);  					
					if ($discount) {
						$price = $this->currency->formatPrice($this->tax->calculate($discount, $result['tax_class_id'], $this->config->get('config_tax')));
					} 
                    else {
						$price = $this->currency->formatPrice($this->tax->calculate($result['price'], $result['tax_class_id'], $this->config->get('config_tax')));					
						$special = $this->model_catalog_product->getProductSpecial($result['product_id']);					
						if ($special) {
							$special = $this->currency->formatPrice($this->tax->calculate($special, $result['tax_class_id'], $this->config->get('config_tax')));
						}					
					}
			        */
                    
                    $price = $this->tax->calculate($result['price'], $result['tax_class_id'], $this->config->get('config_tax'));
                    $price_formatted = $this->currency->formatPrice($price);
                    $discount = 0;
                    $discount_fomatted = 0;
                    $discount_data = $this->model_catalog_discount->getDiscount($result['product_id']); 
                    if($discount_data > 0){
                        $discount = $discount_data;
                        $discount_fomatted =$this->currency->formatPrice($this->tax->calculate($discount_data, $result['tax_class_id'], $this->config->get('config_tax'))); 
                    }
                    
                    $discounts_data = $this->model_catalog_product->getProductDiscounts($result['product_id']);             
                    if($discounts_data){     
                        $discount = $discounts_data[0]['price'];                   
                        $discount_fomatted = $this->currency->formatPrice($this->tax->calculate($discounts_data[0]['price'], $result['tax_class_id'], $this->config->get('config_tax')));
                    }                         
                    $discounts = array();               
                    foreach ($discounts_data as $discount_data) {
                        $discounts[] = array(
                            'quantity' => $discount_data['quantity'],
                            'price'    => $this->currency->formatPrice($this->tax->calculate($discount_data['price'], $result['tax_class_id'], $this->config->get('config_tax')))
                        );
                    }
                      
                    $special = $this->model_catalog_product->getProductSpecial($result['product_id']);        
                    if ($special) {
                        $this->data['special'] = $this->currency->formatPrice($this->tax->calculate($special, $result['tax_class_id'], $this->config->get('config_tax')));
                    } else {
                        $this->data['special'] = FALSE;
                    }
                             
                    $attribute_price = 0; 
                    $min_price = false;  
                    $price_ref = $discount ? $discount : $price;                 
					//$options = $this->model_catalog_product->getProductOptions($result['product_id']);
					$options = $this->model_catalog_product->getActiveProductOptions($result['product_id']);					
                    foreach($options as $option_item){
                        foreach($option_item['option_value'] as $option_value){ 
                            $option_price = (float)$option_value['price'] ? $this->tax->calculate($option_value['price'], $result['tax_class_id'], $this->config->get('config_tax')) : 0;                    
                            if($option_price && ($option_value['prefix'] == '-')){
                                $option_price = -1 * $option_price;                        
                            }
                            
                            if($option_price < $attribute_price){
                                $attribute_price = $option_price;   
                            }
                            
                            if($option_price > 0){
                                $min_price = true;
                            }
                        }
                    }
                     
					$add = $this->model_tool_seo_url->rewrite(HTTP_SERVER . 'index.php?route=product/product&product_id=' . $result['product_id']);
					
					$colors = array();	
					/*
        			$product_colors = $this->model_catalog_product->getProductColors($result['product_id']);			
					foreach ($product_colors as $item) {
						$image_list = $this->model_catalog_product->getProductColorImages($item['product_id'], $item['product_color_id']);
						if(!empty($image_list)){
							$colors[] = array(
								'full'	 	 => HTTPS_IMAGE . $item['image'],		
								//'popup' 	 => $this->model_tool_image->resize($item['image'], 291, 385),			
								'thumb' 	 => $this->model_tool_image->resizeNoScale($item['color_image'], 17, 8),												
							);
						}
					}
					*/
					
                    if($attribute_price != 0){
                        $ref_price =  $this->currency->formatPrice($price_ref + $attribute_price);
                    }
                    elseif($min_price){
                        $ref_price = $this->currency->formatPrice($price_ref);    
                    }
                    else{
                        $ref_price = 0;
                    }

                    $rate_discount = ((floatval($price) - floatval($price_ref)) / floatval($price)) * 100;
                    $rate_discount = round($rate_discount);

                    //$shortname = (strlen($result['name']) <= 16) ? $result['name'] : substr($result['name'], 0 ,16) . ' ...';					
                    $shortname = $this->model_catalog_product->breakProductName($result['name'], 34); 
                    $this->data['products'][] = array(
            			'name'      => $result['name'],
                        'shortname' => $shortname,
						'model'     => $result['model'],
                        //'thumb'     => $this->model_tool_image->resize($image, 121, 148),
                        'thumb'     => $this->model_tool_image->resize($image, 188, 228),
            			'price'     => $price_formatted,
                        'ref_price' => $ref_price, 
                        'discount'  => $discount_fomatted,
                        'discounts' => $discounts,
            			'options'   => $options,
						'special'   => $special,
						'href'      => $this->model_tool_seo_url->rewrite(HTTP_SERVER . 'index.php?route=product/product&path=' . $this->request->get['path'] . '&product_id=' . $result['product_id']),
						'add'	    => $add,
                        'sku'       => $result['sku'],
                    	'colors'	=> $colors,
                        'unbreak'   => mb_strlen($shortname, 'UTF-8') < 34,
                        'rate_discount' => $rate_discount,
          			);
        		} 		
                  
                /*
                $this->data['price_sort']['asc'] = array(
                    'text'      => $this->language->get('text_price_asc'),
                    'value'     => 'Pris Low - Høj',
                    'current'   => $order == 'ASC'  && $sort == 'p.price',
                    'href'      => $this->model_tool_seo_url->rewrite(HTTP_SERVER . 'index.php?route=product/category&path=' . $this->request->get['path'] . '&sort=p.price&order=ASC&limit=' . $limit . $attr_list)
                );  
                $this->data['price_sort']['desc'] = array(
                    'text'      => $this->language->get('text_price_desc'),
                    'value'     => 'Pris Høj - Low',
                    'current'   => $order == 'DESC' && $sort == 'p.price',
                    'href'      => $this->model_tool_seo_url->rewrite(HTTP_SERVER . 'index.php?route=product/category&path=' . $this->request->get['path'] . '&sort=p.price&order=DESC&limit=' . $limit . $attr_list)
                );  
                */
                                 
                $url = HTTP_SERVER . 'index.php?route=product/category&path=' . $this->request->get['path'];
                $this->document->links[] = array(
                    'href' => $this->model_tool_seo_url->rewrite($url),
                    'rel'  => 'canonical'
                );
                $end_url =  '&limit=' . $limit . $attr_list;
                $this->data['sorts'] = array();                                                 
                $this->data['sorts'][] = array(
                    'text'  => $this->language->get('text_newest'),
                    'value' => 'p.date_added-DESC',
                    'href'  => $this->model_tool_seo_url->rewrite($url . '&sort=p.date_added&order=DESC' . $end_url),
                );                  
                $this->data['sorts'][] = array(
                    'text'  => $this->language->get('text_name_asc'),
                    'value' => 'pd.name-ASC',
                    'href'  => $this->model_tool_seo_url->rewrite($url . '&sort=pd.name&order=ASC' . $end_url),
                );  
                $this->data['sorts'][] = array(
                    'text'  => $this->language->get('text_name_desc'),
                    'value' => 'pd.name-DESC',
                    'href'  => $this->model_tool_seo_url->rewrite($url . '&sort=pd.name&order=DESC' . $end_url),
                );
                $this->data['sorts'][] = array(
                    'text'  => $this->language->get('text_price_asc'),
                    'value' => 'p.price-ASC',
                    'href'  => $this->model_tool_seo_url->rewrite($url . '&sort=p.price&order=ASC' . $end_url),
                );  
                $this->data['sorts'][] = array(
                    'text'  => $this->language->get('text_price_desc'),
                    'value' => 'p.price-DESC',
                    'href'  => $this->model_tool_seo_url->rewrite($url . '&sort=p.price&order=DESC' . $end_url),
                );  
                $this->data['sorts'][] = array(
                    'text'  => $this->language->get('text_default'),
                    //'value' => 'p.sort_order-ASC',                    
                    'value' => 'pcs.product_sort_order-ASC',
                    'href'  => $this->model_tool_seo_url->rewrite($url . '&sort=pcs.product_sort_order&order=ASC' . $end_url),
                );  
                /*
                $this->data['sorts'][] = array(
                    'text'  => $this->language->get('text_manufacture_asc'),
                    'value' => 'm.name-ASC',
                    'href'  => $this->model_tool_seo_url->rewrite($url . '&sort=m.name&order=ASC' . $end_url),
                );  
                */
                
				$this->data['limits'] = array();
				/*
                $this->data['limits'][] = array(                    
                    'value'     => 12,
                    'current'   => $limit == 12,
                    'href'      => $this->model_tool_seo_url->rewrite($url . '&sort=' . $sort . '&order=' . $order . '&limit=12' . $attr_list)
                );
				*/
                $this->data['limits'][] = array(                    
                    'value'     => 24,
                    'current'   => $limit == 24,  
                    'href'      => $this->model_tool_seo_url->rewrite($url . '&sort=' . $sort . '&order=' . $order . '&limit=24'. $attr_list)
                );
                
                $this->data['limits'][] = array(                    
                    'value'     => 36,
                    'current'   => $limit == 36,  
                    'href'      => $this->model_tool_seo_url->rewrite(HTTP_SERVER . 'index.php?route=product/category&path=' . $this->request->get['path'] . '&sort=' . $sort . '&order=' . $order . '&limit=36' . $attr_list)
                );
                $this->data['limits'][] = array(                    
                    'value'     => 'Alle',
                    'current'   => $limit == 0,  
                    'href'      => $this->model_tool_seo_url->rewrite(HTTP_SERVER . 'index.php?route=product/category&path=' . $this->request->get['path'] . '&sort=' . $sort . '&order=' . $order . '&limit=none' . $attr_list)
                );		
			
                $url = '&sort=' . $sort . '&order=' . $order . '&limit=' . $limit . $attr_list;
				$pagination = new Pagination();
				$pagination->total = $product_total;
				$pagination->page = $page;
				$pagination->limit = $limit; 
				$pagination->text = $this->language->get('text_pagination');
				$pagination->url = $this->model_tool_seo_url->rewrite(HTTP_SERVER . 'index.php?route=product/category&path=' . $this->request->get['path'] . $url . '&page={page}');			
				$this->data['pagination'] = $pagination->renderPaging();

				$this->load->model('setting/tooltip'); 
				$this->data['shipping_note'] = $this->model_setting_tooltip->getShippingNote();
				
			    $this->data['text_error'] = $this->language->get('text_empty');
				if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/product/category.tpl')) {
					$this->template = $this->config->get('config_template') . '/template/product/category.tpl';
				} else {
					$this->template = 'default/template/product/category.tpl';
				}
				
				$this->children = array(
					'common/header',
                    'common/footer',
                    //'common/column_left_product',
					'common/column_left',
                    'module/category',
                    'module/services',
                    'module/newsletter',
				);

                $this->data['lazy_load'] = array(
                    'total'     => $pagination->total,
                    'page'      => $pagination->page,
                    'limit'     => $pagination->limit,
                    'url'       => $pagination->url,
                );
                if (isset($this->request->get['lazy_load']) && $this->request->get['lazy_load']) {
                    if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/product/category_lazyload.tpl')) {
                        $this->template = $this->config->get('config_template') . '/template/product/category_lazyload.tpl';
                    }
                    else {
                        $this->template = $this->config->get('config_template') . '/template/product/search.tpl';
                    }
                }

                $this->response->setOutput($this->render(TRUE), $this->config->get('config_compression'));
      		} else {
        		$this->document->title = $category_info['name']; 				
				$this->document->description = $category_info['meta_description'];

        		$this->data['text_error'] = $this->language->get('text_empty');
        		$this->data['button_continue'] = $this->language->get('button_continue');  
                $this->data['breadcrumbs'] = $this->document->breadcrumbs; 
        		
                $this->data['continue'] = HTTP_SERVER . 'index.php?route=common/home';
		        $this->data['back_product'] = $this->model_tool_seo_url->rewrite(HTTP_SERVER . 'index.php?route=product/categories');

                $this->data['heading_title'] = $category_info['name'];
                $this->data['description'] = html_entity_decode($category_info['description'], ENT_QUOTES, 'UTF-8');

                $this->data['pagination'] = '';
                $this->data['products'] = array();
                $this->data['categories'] = $this->model_catalog_category->getCategories($category_info['category_id']);
                
				if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/product/category_children.tpl')) {
					$this->template = $this->config->get('config_template') . '/template/product/category_children.tpl';
				} else {
					$this->template = 'default/template/product/category.tpl';
				}

                $this->children = array(
					'common/header',
                    'common/footer',
					//'common/column_left_product',							
                    'common/column_left',
                    'module/category',
                    'module/services',
                    'module/newsletter',
				);

				$this->response->setOutput($this->render(TRUE), $this->config->get('config_compression'));
      		}
    	} else {
			$url = '';    			
			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}	
			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}  				
			if (isset($this->request->get['page'])) {
				$url .= '&page=' . $this->request->get['page'];
			}	
            if (isset($this->request->get['limit'])) {
                $url .= '&limit=' . $this->request->get['limit'];
            }
			
			if (isset($this->request->get['path'])) {	
	       		$this->document->breadcrumbs[] = array(
   	    			'href'      => $this->model_tool_seo_url->rewrite(HTTP_SERVER . 'index.php?route=product/category&path=' . $this->request->get['path'] . $url),
    	   			'text'      => $this->language->get('text_error'),
        			'separator' => $this->language->get('text_separator')
        		);
			}

			$this->document->title = $this->language->get('text_error');

      		$this->data['heading_title'] = $this->language->get('text_error');
      		$this->data['text_error'] = $this->language->get('text_error');   
      		$this->data['button_continue'] = $this->language->get('button_continue');  
      		
            $this->data['continue'] = null; //HTTP_SERVER . 'index.php?route=common/home';                  
			//$this->data['continue'] = $this->model_tool_seo_url->rewrite(HTTP_SERVER . 'index.php?route=product/categories');
            //$this->data['image_name'] = 'bt_tibagetilprodukter.png'; 
            
			if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/error/not_found.tpl')) {
				$this->template = $this->config->get('config_template') . '/template/error/not_found.tpl';
			} 
            else {
				$this->template = 'default/template/error/not_found.tpl';
			}				
                
			$this->children = array(
				'common/header',
                'common/footer',
                'common/column_left',
			);
		
			$this->response->setOutput($this->render(TRUE), $this->config->get('config_compression'));
		}
  	}
}
?>